<?php

namespace app\index\controller;

use app\data\model\ActActivity;
use app\data\model\ActArticleModel;
use app\data\model\ActOrder;
use app\data\model\ActUserModel;
use app\index\service\EmailService;
use app\index\service\LoginUserService;
use think\helper\Str;

class Index extends BaseController
{
    //主页
    //推荐条目数
    const INDEX_RECOMMEND_ITEM_NUM = 6;

    /**
     * 主页
     * @return void
     */
    public function index()
    {
        

        //轮播
        $this->topCarousel = sysdata('sliderHomePage');
        //推荐
        // $this->recommend = ActArticleModel::where('cat_id', 3)
        //     ->limit(0, self::INDEX_RECOMMEND_ITEM_NUM)
        //     ->order('id desc')
        //     ->select();
        
      
        $this->recommend = ActActivity::where('un_public',0)->where('status',1)->field('id,name,begin_time,end_time,abstract,logo')->order('id desc')->limit(9)->select();
        $this->fetch();
    }


    //登录
    public function login()
    {
        $data = $this->_vali([
            'email.require' => '邮箱不能为空！',
            'email.email' => '邮箱格式错误！',
            'password.require' => '密码不能为空',
        ]);
        $user = ActUserModel::where('email', $data['email'])->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }

        if (!$user->checkPassword($data['password'])) {
            $this->error('密码错误');
        }

        if ($user->ifForbid()) {
            $this->error('用户已禁止登录，请联系管理员处理！');
        }

        LoginUserService::login($user->toArray());

        $this->success('登录成功');
    }

    //注册
    public function register()
    {
        $data = $this->_vali([
            'email.require'                     => '邮箱不能为空！',
            'email.email'                       => '邮箱格式错误！',
            'password.require'                  => '密码不能为空',
            'password.min:4'                    => '密码最少4个字符',
            'password.max:20'                   => '密码不能超过20个字符',
            'password.alphaNum'                 => '密码只能由字母、数字组成',
            'password_confirm.require'          => '请确认密码必须！',
            'password_confirm.confirm:password' => '两次密码不一致！',
            'phone.require'                     => '手机号不能为空',
            'phone.mobile'                      => '手机号格式错误！',
            'email_check_code.require'          => '缺少邮箱验证码！',
        ]);
        $data['pid']       = input('post.pid/d',0);
        $data['name']      = input('post.name','');
        $data['roles_arr'] = input('post.roles/a',[]);
        if(count($data['roles_arr'])){
            $data['roles'] = implode(',',$data['roles_arr']);
        }else{
            //默认全部权限
            $data['roles'] = '1,2,3,4';
        }
        //验证邮箱验证码
        if (!$this->checkEmailCheckCode($data['email'], $data['email_check_code'])) {
            $this->error('邮箱验证码错误！');
        }

        ActUserModel::createUser($data);
        $this->success('注册成功！');
    }

    //发送注册邮箱验证码
    public function sendEmailCheckCode()
    {
        $this->_vali(['email.require' => '缺少接收邮箱！', 'email.email' => '邮箱格式错误！']);
        $email = input('email');
        if(ActUserModel::where('email',$email)->count()) return $this->error('该邮件已注册');
        $code = $this->getEmailCheckCode($email);
        $res = EmailService::sendHtml($email, "注册邮箱验证码", "<p>欢迎注册本网站，您的邮箱验证码为 <h2>{$code}</h2></p>");
        if ($res) {
            $this->success('邮箱验证码发送成功，请前往邮箱查收！');
        } else {
            $this->error('邮件擦送错误！');
        }
    }

    //获取邮件验证码
    private function getEmailCheckCode($email)
    {
        $code = Str::random(6);

        $save_key = 'register_email_code';
        $code_arr = session($save_key) ?: [];
        $code_arr[$email][] = $code;
        session($save_key, $code_arr);

        return $code;
    }

    //验证邮箱验证码
    private function checkEmailCheckCode($email, $code)
    {
        $save_key = 'register_email_code';
        $cache = session($save_key) ?: [];
        $code_arr = $cache[$email] ?? [];
        return in_array($code, $code_arr);
    }

    //登出
    public function logout()
    {
        if (!LoginUserService::ifLogin()) {
            $this->error('禁止访问！');
        }
        LoginUserService::logout();
        $this->success('登出成功');
    }
}